import 'dart:io';

import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:webview_flutter_plus/webview_flutter_plus.dart';
import 'package:path/path.dart' as p;

import '../../server/local_web_server.dart';
import '../../values/color_value.dart';
import '../../values/style_value.dart' show StyleValue;

class FileServerPage extends StatefulWidget {
  const FileServerPage({super.key});

  @override
  State<FileServerPage> createState() => _FileServerPageState();
}

class _FileServerPageState extends State<FileServerPage> {
  late LocalWebServer _server;
  String? _serverBaseUrl;
  List<File> _selectedFiles = [];
  List<String> _downloadUrls = [];
  String? _deviceIp;


  @override
  void initState() {
    super.initState();
    _checkPermissions();
    _startServer();
    _getDeviceIp();
  }




  // 检查存储权限（Android）
  Future<void> _checkPermissions() async {
    if (Platform.isAndroid) {
      final status = await Permission.storage.request();
      if (!status.isGranted) {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('需要存储权限才能选择文件')),
          );
        }
      }
    }
  }

  // 启动本地服务器
  Future<void> _startServer() async {
    _server = LocalWebServer(port: 8080);
    final url = await _server.start();
    setState(() => _serverBaseUrl = url);
  }

  // 获取设备内网IP
  Future<void> _getDeviceIp() async {
    final interfaces = await NetworkInterface.list();
    for (var interface in interfaces) {
      for (var addr in interface.addresses) {
        if (addr.type == InternetAddressType.IPv4 && !addr.isLoopback) {
          setState(() => _deviceIp = addr.address);
          return;
        }
      }
    }
  }

  // 选择文件
  Future<void> _pickFiles() async {
    final result = await FilePicker.platform.pickFiles(
      allowMultiple: true,
      type: FileType.any,
    );

    if (result != null) {
      final files = result.paths.map((path) => File(path!)).toList();
      setState(() => _selectedFiles = files);
      _server.updateSelectedFiles(files);
      _generateDownloadUrls();
    }
  }

  // 生成下载链接
  void _generateDownloadUrls() {
    if (_deviceIp == null || _serverBaseUrl == null) return;
    _downloadUrls = _selectedFiles.map((file) {
      final filename = p.basename(file.path);
      return 'http://$_deviceIp:8080/download/$filename';
    }).toList();
  }

  // 复制链接到剪贴板
  void _copyToClipboard(String url) {
    Clipboard.setData(ClipboardData(text: url));
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('下载链接已复制')),
    );
  }

  @override
  void dispose() {
    _server.stop();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: StyleValue.getAppBar('本地文件服务器'),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            if (_deviceIp != null)
              Padding(padding: StyleValue.contentInnerPadding,
                child: Text('服务器地址：http://$_deviceIp:8080', style: const TextStyle(color: Colors.green)),),

            Padding(padding: StyleValue.contentInnerPadding,child:  ElevatedButton.icon(
              icon: const Icon(Icons.file_open),
              label: const Text('选择文件'),
              onPressed: _pickFiles,
            )),

            Padding(padding: StyleValue.contentInnerPadding,
              child: const Text('已选择文件：', style: TextStyle(fontWeight: FontWeight.bold))),

            Expanded(
              child: _selectedFiles.isEmpty
                  ? const Center(child: Text('未选择文件'))
                  : ListView.builder(
                itemCount: _selectedFiles.length,
                itemBuilder: (context, index) {
                  final file = _selectedFiles[index];
                  final url = _downloadUrls.isNotEmpty ? _downloadUrls[index] : '';
                  return Card(
                    child: ListTile(
                      title: Text(p.basename(file.path)),
                      subtitle: url.isNotEmpty ? Text('下载链接：$url') : null,
                      trailing: IconButton(
                        icon: const Icon(Icons.copy),
                        onPressed: url.isNotEmpty ? () => _copyToClipboard(url) : null,
                      ),
                    ),
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}